package com.block.datapush.service.apipush;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.model.vo.SourceDictVO;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 漳州 筛选身份证
 */
@Service
public class XiaMenPushApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMemberCommonService memberCommonService;

    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);


        if (!StrUtil.startWith(memberSourceInfo.getIdcard(), "3506") && !StrUtil.startWith(memberSourceInfo.getIdcard(), "3505")) {
            pushApiResult.setMessage("身份证过筛失败");
            pushApiResult.setCode("400");
            return pushApiResult;
        }

        String queryUrl = pushApiKeyParam.getCheckUrl();
        String mobileMd5 = memberSourceInfo.getMobileMd5();

        JSONObject bizMap = new JSONObject();
        bizMap.put("phone", mobileMd5);

        JSONArray dataArray = new JSONArray();
        dataArray.add(bizMap);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("accessKey", pushApiKeyParam.getApiSecret());
        paramMap.put("requestId", UUID.fastUUID().toString());
        paramMap.put("data", dataArray);

        log.info("【厦门行知远】撞库开始【queryUrl】{}【bizParam】{}", queryUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【厦门行知远】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");
        boolean success = resultObject.getBoolean("success");
        JSONArray resultArray = resultObject.getJSONArray("data");

        pushApiResult.setCode(String.valueOf(code));
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "200") && success) {
            if (ObjectUtil.isEmpty(resultArray)) {
                pushApiResult.setPushSuccess(true);
            }
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        return null;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        String requestUrl = pushApiKeyParam.getRegisterUrl();

        String provinceCode = memberSourceInfo.getProvinceCode();
        String cityCode = memberSourceInfo.getCityCode();

        SourceDictVO sourceDictVO = memberCommonService.queryDictInfoByValue(memberSourceInfo.getLoanAmount());
        String loanAmount = sourceDictVO.getExtValue() + "0000";

        Map<String, String> item = new HashMap<>();
        item.put("t1", memberSourceInfo.getMobile());
        item.put("t2", memberSourceInfo.getRealname());
        item.put("t3", "1");
        item.put("t4", loanAmount);//  意向金额
        item.put("t5", "0");
        item.put("t6", "0");
        item.put("t7", pushApiKeyParam.getApiCode());
        item.put("t8", provinceCode);

        item.put("t9", cityCode);
        item.put("t10", this.getUserInfo(memberSourceInfo));

        Map<String, String> bizMap = this.getRsaParam(item, pushApiKeyParam.getPubKey());

        JSONArray dataArray = new JSONArray();
        dataArray.add(bizMap);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("accessKey", pushApiKeyParam.getApiSecret());
        paramMap.put("requestId", UUID.fastUUID().toString());
        paramMap.put("data", dataArray);

        log.info("【厦门行知远】导单开始【requestUrl】{}【paramMap】{}", requestUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【厦门行知远】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");
        boolean success = resultObject.getBoolean("success");
        JSONArray resultArray = resultObject.getJSONArray("data");

        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (ObjectUtil.equal(code, Integer.valueOf(200)) && success) {
            String oneResult = resultArray.getString(0);
            if (StrUtil.equals("第1行数据成功", oneResult)) {
                pushApiResult.setPushSuccess(true);
                pushApiResult.setSettleFlag(true);
                pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
                return pushApiResult;
            }
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();

        return pushApiResult;
    }

    private String getUserInfo(MemberSourceInfo memberSourceInfo) {
        String sex = ObjectUtil.equals(memberSourceInfo.getSex(), 1) ? "男" : "女";
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder
                .append("城市：" + memberSourceInfo.getCity()).append("；")
                .append("年龄：" + memberSourceInfo.getAge()).append("；")
                .append("性别：" + sex).append("；")
                .append("房产：").append(memberCommonService.queryDictInfoByValue(memberSourceInfo.getHouse()).getName()).append("；")
                .append("车产：").append(memberCommonService.queryDictInfoByValue(memberSourceInfo.getCar()).getName()).append("；")
                .append("公积金：").append(memberCommonService.queryDictInfoByValue(memberSourceInfo.getGjj()).getName()).append("；")
                .append("逾期情况：").append(memberCommonService.queryDictInfoByValue(memberSourceInfo.getYuqi()).getName()).append("；")
                .append("社保：").append(memberCommonService.queryDictInfoByValue(memberSourceInfo.getShebao()).getName()).append("；")
                .append("保险：").append(memberCommonService.queryDictInfoByValue(memberSourceInfo.getBaoxian()).getName()).append("；")
                .append("芝麻分：").append(memberCommonService.queryDictInfoByValue(memberSourceInfo.getZhima()).getName()).append("；")
                .append("白条：").append(memberCommonService.queryDictInfoByValue(memberSourceInfo.getBaitiao()).getName()).append("；")
                .append("花呗：").append(memberCommonService.queryDictInfoByValue(memberSourceInfo.getHuabei()).getName()).append("；")
        ;
        return stringBuilder.toString();
    }


    private Map<String, String> getRsaParam(Map<String, String> bizMap, String pubKey) {

        List<String> keyList = JSON.parseArray(JSON.toJSONString(bizMap.keySet()), String.class);
        Collections.sort(keyList);

        Map<String, String> resultMap = new HashMap<>();
        StringBuilder signBuilder = new StringBuilder();
        for (String key : keyList) {
            String value = bizMap.get(key);
            signBuilder.append(key).append(value);

            log.info("【庆鱼2】数据加密【key】{}【value】{}", key, value);
            resultMap.put(key, this.getRsaResult(value, pubKey));
        }

        String signContent = SecureUtil.md5(signBuilder.toString()).toUpperCase(Locale.ROOT);
        resultMap.put("sign", this.getRsaResult(signContent, pubKey));

        return resultMap;
    }

    private String getRsaResult(String content, String pubKey) {
        RSA rsa = new RSA(null, pubKey);
        String rsaContent = rsa.encryptBase64(content, KeyType.PublicKey);
        return rsaContent;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        return null;
    }
}
